import {Button, message, Select, Switch} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryRule,exportSettleDetails,exportSettle,changeStatus} from './service';
import {saveFileAs} from '@/utils/utils';
import CreateForm from "@/pages/OrderManagement/StoreOrder/components/CreateForm";
import styles from "@/global.less";
import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import Access from '@/components/Access/Access';
const TableList = (props) => {
  const actionRef = useRef();
  const [storeArray, setStoreArray] = useState([]);
  const [count, setCount] = useState();
  const [settleDetails, setSettleDetails] = useState(false);
  const [settleRecords, setSettleRecords] = useState(false);
  const [outModal, handleOutModal] = useState(false);
  const [recordLoading, setRecordLoading] = useState(false);
  const [changeFlag, setChangeFlag] = useState(false);
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getStore();
  }, []);
  const onChange = (checked) => {
    setChangeFlag(checked);
  };
  const columns = [
    {
      title: '结算店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择结算店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options){
                option.options.map((data=>{
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }))
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id} >
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '结算店铺',
      dataIndex: 'storeName',
      hideInSearch:true,
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '结算周期',
      dataIndex: 'settleType',
      valueEnum: {
        3: {
          text: '自营周结',
          status: 'Processing',
        },
        4: {
          text: '自营月结',
          status: 'Success',
        },
        // 5: {
        //   text: '一店一超月结',
        //   status: 'Error',
        // },
      },
    },
    {
      title: '结算时间',
      dataIndex: 'settleDate',
      valueType: 'date',

    },
    {
      title: '当期收款金额',
      dataIndex: 'orderSettleMoney',
      hideInSearch: true,
    },
    {
      title: '当期退款金额',
      dataIndex: 'refundSettleMoney',
      hideInSearch: true,
    },
    {
      title: '当期公司成本',
      dataIndex: 'costSettleMoney',
      hideInSearch: true,
    },
    {
      title: '入账金额',
      dataIndex: 'totalSettleMoney',
      hideInSearch: true,
    },
    // {
    //   title: '提成金额',
    //   dataIndex: 'commissionSettleMoney',
    //   hideInSearch: true,
    // },
    {
      title: '处理状态',
      dataIndex: 'settleStatus',
      hideInForm: true,
      render: (dom, record) => {
        return (
          <Access accessKey={"@updateSettleStatus"}>
            <Switch
              key={record.id}
              checked={record.settleStatus}
              loading={recordLoading}
              onChange={(e)=>{
                setRecordLoading(true);
                changeStatus({
                  id:record.id,
                  settleStatus:e
                }).then(res=>{
                  setRecordLoading(false);
                  actionRef.current.reload();
                });
              }} />
          </Access>
        );
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <div>
            <Switch onChange={onChange} />
          </div>
        );
      },
    },
    {
      title: '操作',
      width:80,
      valueType: 'option',
      render: (_, record) => (
        <Access accessKey={"@downloadSettleOrderDetails"}>
          <Button
            type="dashed"
            shape="round"
            ghost
            danger
            block
            loading={settleDetails}
            onClick={() => {
              setSettleDetails(!settleDetails);
              exportSettleDetails(record.id).then(res=>{
                if (res){
                  saveFileAs(res, '账单明细');
                }
                setSettleDetails(false);
              })
            }}
          >
            账单明细
          </Button>
        </Access>
      ),
    },
  ];
  const outColumns = [
    {
      title: '结算时间',
      dataIndex: 'settleDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '结算时间为必选项',
          },
        ],
      },
    },
    {
      title: '结算店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择结算店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options){
                option.options.map((data=>{
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }))
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id} >
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="结算列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1200}}
        bordered
        onReset={()=>{
          setChangeFlag(false);
        }}
        footer={() => {
          return (
            <div key="settleFooter" style={{ color: 'red' }}>
              <span>说明：</span>
              <div>* 当期收款金额为该结算周期内发生的订单金额</div>
              <div>* 当期退款金额为该结算周期之前的订单在该结算周期内退款的订单金额</div>
              <div>* 入账金额计算方式： 入账金额=(当期收款金额-当期退款金额)</div>
            </div>
          );
        }}
        toolBarRender={() => [
          <Access accessKey={"@exportSettleDetails"}>
            <Button loading={settleRecords} type="primary" onClick={() => {
              handleOutModal(true);
              setSettleRecords(true);
            }}>
              导出结算记录
            </Button>
          </Access>

        ]}
        request={(params, sorter, filter) => {
          params.settleStatus = changeFlag;
         return queryRule({...params, sorter, filter});
        }}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />
      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => {
          handleOutModal(false);
          setSettleRecords(false);
        }}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutModal(false);
            exportSettle(value).then(res=>{
              if (res){
                saveFileAs(res, '结算记录');
              }
              setSettleRecords(false);
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
